package com.ymtc.ibm.code;

import com.ibm.mq.*;
import com.ibm.mq.constants.MQConstants;

public class MQClientPutExpiry {

	private String hostname = "10.41.192.200";
	private int port = 1414; 
	private String channel = "CLIENT.CHL"; 
	private String qManager = "QM01"; 
	private MQQueueManager qMgr; 
	private static String qName = "QTEST";
	private static String qReport = "Q.NULL";
	private MQQueue queue;

	public static void main(String[] args) {		
		MQClientPutExpiry mqc = new MQClientPutExpiry();
		mqc.runPutMsg();
	}

	public void MQStart() {
		try {
			//MQEnvironment.properties.put(CMQC.TRANSPORT_PROPERTY,CMQC.TRANSPORT_MQSERIES_CLIENT);
			MQEnvironment.hostname = hostname; 
			MQEnvironment.channel = channel; 
			MQEnvironment.port = port;
			MQEnvironment.CCSID = 819;
			
			qMgr = new MQQueueManager(qManager);
			int openOptions = MQConstants.MQOO_OUTPUT | MQConstants.MQOO_FAIL_IF_QUIESCING | MQConstants.MQOO_BIND_NOT_FIXED ;
			queue = qMgr.accessQueue(qName, openOptions);
			System.out.println(">>> Open Queue successful!");
		} catch (Exception ex) {
			ex.printStackTrace(System.out);
		}
	}

	public void MQStop() {
		try {
			queue.close();
			qMgr.disconnect();
		} catch (MQException ex) {
			System.out.println("stop err!!!!");
		}
	}

	public void sendMsgToQueue() {
		try {
			MQPutMessageOptions pmo = new MQPutMessageOptions();
			//pmo.options = pmo.options + MQConstants.MQPMO_LOGICAL_ORDER;

			MQMessage msg = new MQMessage();
			System.out.println(">>> MQMD version is : " + msg.getVersion());
			msg.characterSet = 819;
			msg.expiry = 10;
			msg.report = MQConstants.MQRO_EXPIRATION_WITH_DATA;
			msg.replyToQueueName = qReport;
			msg.replyToQueueManagerName = "QM01";
					
			int number=1;
			int groupNum=3;
			while (number <= groupNum) {
				if (number ==1) {
					msg.persistence = MQConstants.MQPER_PERSISTENT;
					msg.writeString("<Manifest><Head_Info><SenderID>0906000000001</SenderID><ReceiverID>0908</ReceiverID></Head_Info>");
				}
				if (number ==2) {
					msg.persistence = MQConstants.MQPER_PERSISTENT;
					msg.writeString("<Body><DeclarationOfficeID>0908</DeclarationOfficeID><UnloadingLocation><ID>09060000001</ID><ArrivalDate>20110519000000328</ArrivalDate>");
				}
				if (number ==3) {
					msg.persistence = MQConstants.MQPER_NOT_PERSISTENT;
					msg.writeString("</UnloadingLocation><TransportEquipment><EquipmentIdentification><ID>CAIU2040426</ID></EquipmentIdentification><CharacteristicCode></CharacteristicCode><FullnessCode></FullnessCode></TransportEquipment></Body></Manifest>");
				}
				queue.put(msg, pmo);
				System.out.println(">>> Put message OK --- ");
				msg.clearMessage();	
				number++;
				//Thread.sleep(30000);
			}
		} catch (Exception ex) {
			ex.printStackTrace(System.out);
		}
	}

	public void runPutMsg() {
		try {
			MQStart();
			sendMsgToQueue();
			MQStop();
		} catch (Exception e) {
			e.printStackTrace(System.out);
			MQStop();
			System.exit(2);
		}
	}
}